package com.sfac;

import com.sfac.modules.common.vo.Search;
import com.sfac.modules.test.mapper.StudentMapper;
import com.sfac.modules.test.pojo.Card;
import com.sfac.modules.test.pojo.Student;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import org.springframework.test.context.junit4.SpringRunner;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {HqyjSpringbootApplication.class})
public class HqyjSpringbootApplicationTestJpa {
    @Autowired
    private StudentMapper studentMapper;

    /**
     * 测试添加方法
     */
    @Test
    public void testAdd(){
       Student student = new Student();
       student.setStudentName("唐琳5");
       Card card = new Card();
       card.setCardNum("2011505");
       student.setStudentCard(card);
       studentMapper.saveAndFlush(student);

    }

    /**
     * 测试修改方法
     */
    @Test
    public void testUpdate(){

        Student student = new Student();
        student.setId(4);
        student.setStudentName("唐琳100");
        studentMapper.saveAndFlush(student);

        studentMapper.save(student);
    }


    /**
     * 测试查询方法
     */
    @Test
    public void testSelect(){
        log.info("查询数据为{}",studentMapper.findAll());
    }


    /**
     * 测试分页查询
     */
    @Test
    public void testSearch(){
        // 初始化查询对象
        Search search = new Search();
        search.init();

        /**
         * 定义排序规则和排序字段
         */
        Sort sort = Sort.by(
                search.getDirection().equalsIgnoreCase("asc")?
                        Sort.Direction.ASC:Sort.Direction.DESC,
                search.getSort()
        );

        /**
         * 定义分页的数据
         */
        PageRequest pageable = PageRequest.of(search.getCurrentPage()
                ,search.getPageSize(),sort);

        /**
         * 定义查询规则
         */
        Student student = new Student();
        student.setStudentName(search.getKeyWord());
        ExampleMatcher matcher = ExampleMatcher
                .matchingAny()
                .withMatcher("studentName",matcher1 -> matcher1.contains())// 查询的规则
                .withIgnorePaths("id");// 忽略字段

        Example<Student> example = Example.of(student,matcher);

        Page page = studentMapper.findAll(example,pageable);
        log.info("jpa查询到的数据为{}",page);
    }


    @Test
    public void testSelectByName(){
        log.info("查询的到的数据为:{}",studentMapper.findByStudentName("唐琳"));
    }


}
